Intro
I will keep my notes of the Go lang here.
Packages
Every Go Program is made up of packages. programs start running in package ‘main’ - the ‘main’ package is unique because it is the entry point to the program, only one source file can use ‘package main’
Go import packages using the import statement with the associated import path for that package. Go searches for that package in the GOPATH env variable.
import (
"fmt",
"math/rand"
)
every source file must belong to packages
to import subpackages, use the following import path:
import "parent_package/sub_package"
by convention the package name is the same as the last element in the import path
Exports from Packages Go only exports those identifiers that start with an upper-case letter,
if it doesn’t start with an upper-case, it isn’t accessible outside the file.
Variables
var declares a list of variables and the type goes last
a var statement can be at package or function level
var arg1, arg2, arg3 int
or
var arg1, arg2, arg3 = true, "Hello", 1
a var statement can include initializers, one per variable, and and the type can be left off if initializers are provided
‘:=’ can be used inside of functions with implicit type declarations, this is unavailable outside of functions because every statement begins with a keyword: var, func, etc.
- type declarations in Go look like
int
x
total float*int
ref [3]int
array []string slice
type declarations use a left-to-right reading/parsing method
it deviates from the C-style type declarations where the type declaration came before the identifier:
This style becomes increasingly harder to parse as the the type declaration becomes further recursive:
int (*fp)(int (*ff)(int x, int y), int b)
a function pointer that takes a another pointer to function as an argument that takes 2 ints, x & y, and another int argument
expressions involving pointers and slices looks like in Go:
= array[0]
x = * value
function declarations look like the following:
func
if you have multiple consecutive arguements that all share the same type then you only need to specify the type on the last argument
func (arg1, arg2, arg3 int, arg4 string, arg5, arg6 float)
References
https://go.dev/blog/declaration-syntax